﻿/*
网站通用JS

*/
if ("".trim === undefined)
	String.prototype.trim = function () {
		// 用正则表达式将前后空格  
		// 用空字符串替代 
		return this.replace(/(^\s*)|(\s*$)/g, "");
	}
if ("".startsWith === undefined)
	String.prototype.startsWith = function (str) {
		return (this.match("^" + str) == str)
	}
if ("".endsWith === undefined)
	String.prototype.endsWith = function (str) {
		return (this.match(str + "$") == str)
	}
window.Kmer = function (options) {
    this.gotoIFrame = 'Home.aspx';

	var serverTime = 0;
	var serverLocalDiffTime = 0;
	this.UseUserToken = false;
	this.UseAccessToken = false;
    this.getUserToken=function() {
        return sessionStorage.getItem("USER-ACCESS-TOKEN");
    }
    this.getToken = function () {
        return localStorage.getItem("API-ACCESS-TOKEN");
    }
    this.getUrlParam = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    };
	this.setServerTime = function(time) {
		serverTime = time;
		var localDate = new Date();
		serverLocalDiffTime = parseInt(serverTime - localDate.getTime());
	};
	this.getDate = function() {
		var localDate = new Date();
		return new Date(localDate.getTime() + serverLocalDiffTime);
	};
	this.AppRootPath = '/';
	$.extend(this, options);
	var pageFile = this.CurrentUrl;
	if (this.CurrentUrl.indexOf('?') > 0) {
		var tmp = this.CurrentUrl.split('?');
		pageFile = tmp[0];
		this.QueryString = tmp[1];
	} else {
		this.QueryString = '';
	}
	var arr = pageFile.split('/');
	if(arr.length > 1)arr.pop();
	this.CurrentPath = arr.join('/') + '/';

   if(this.getUrlParam("usertoken")) {
       sessionStorage.setItem("USER-ACCESS-TOKEN", this.getUrlParam("usertoken"));
   }

	this.ShowLoading = this.ShoeLoading = function () {
		layer.load(2, { 'shade': [0.1, '#000'] });
	}
	//this.AuthUser = function () {
	//    var redirectUri = encodeURIComponent("http://www.Kmer.com/WPage/WeOAuth.aspx?return_url=" + encodeURIComponent(location.href));
	//    var scope = "snsapi_base";
	//    var state = "js";
	//    var a = ["https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxdbc70ef4e927a7b7&redirect_uri=",
    //        redirectUri,
    //        "&response_type=code&scope=", scope, "&state=", state, "#wechat_redirect"];
	//    location.href = a.join("");
	//};
	this.GetPath = function (path, pBaseUrl) {
		if (!pBaseUrl) {
			pBaseUrl = this.CurrentPath;
		}
		path = path.replace(/\\/ig, '/');
		if(path.startsWith('http://') || path.startsWith('https://') || path.startsWith('/')) {
			return path;
		}else if (path.startsWith('~/')) {
			return this.AppRootPath + path.substr(2);
		} else if (path.startsWith('./')) {
			return pBaseUrl + path.substr(2);
		} else if (path.startsWith('../')) {
			arr = pBaseUrl.split('/');
			arr.pop();
			if (arr.length > 1) {
				arr.pop();
			}
			var baseUrl= arr.join('/') + '/';
			return this.GetPath(path.substr(3), baseUrl)
		} else {
			return pBaseUrl + path;
		}
	};
	this.API2 = function (control, action, data, callBack) {
	    var a = ["/api.ashx?c=", control, "&a=", action,"&u=", this.getUserToken()];
	    if (this.UseAccessToken) {
            a.push("&token=");
            a.push(this.getToken());
        }

	    var url = a.join("");
            
		$.ajax({
			type: 'POST',
			url: this.GetPath(url),
			data: data,
			dataType: "json",
			contentType: "application/json",
			beforeSend: function () {},
			success: function (data) {
				if (callBack != null) {
					if (data == null) {
						callBack({ "Success": false, "Message": '没有返回' });
					} else if (data.Success) {
						callBack(data.Data);
					} else if (data.Success === false) {
                        if (data.Code == 4009) {
                            //window.parent.location.href = location.origin + "/login.aspx";
                            window.parent.location.href = "../login.aspx";
					    } else {
					        callBack(data);
					    }
					} else if ($.type(data.d) === "string") {
						callBack($.parseJSON(data.d));
					} else {
						callBack(data.d);
					}
				}
			}
		});
		return this;
	}
	this.API3 = function (control, action, data, callBack) {
	    var a = ["/api.ashx?c=", control, "&a=", action, "&u=", this.getUserToken()];
	    if (this.UseAccessToken) {
	        a.push("&token=");
	        a.push(this.getToken());
	    }

	    var url = a.join("");

	    $.ajax({
	        type: 'POST',
	        url: this.GetPath(url),
	        data: data,
	        dataType: "json",
	        async: false,
	        contentType: "application/json",
	        beforeSend: function () {
	        },
	        success: function (data) {
	            if (callBack != null) {
	                if (data == null) {
	                    callBack({ "Success": false, "Message": '没有返回' });
	                } else if (data.Success) {
	                    callBack(data.Data);
	                } else if (data.Success === false) {
	                    if (data.Code == 4009) {
	                        //window.parent.location.href = location.host + "/login.aspx";
	                        window.parent.location.href = "../login.aspx";
	                    } else {
	                        callBack(data);
	                    }
	                } else if ($.type(data.d) === "string") {
	                    callBack($.parseJSON(data.d));
	                } else {
	                    callBack(data.d);
	                }
	            }
	        }
	    });
	    return this;
	}
	var __api_call_list = {};
	this.RequestAPI = function (control, action, data, cacheTimeOut) {
	    console.log(control, action, !$.isNumeric(cacheTimeOut));
	    if (!$.isNumeric(cacheTimeOut)) cacheTimeOut = 0;
	    var a = ["/api.ashx?c=", control, "&a=", action, "&u=", this.getUserToken()];
	    if (this.UseAccessToken) {
	        a.push("&token=");
	        a.push(this.getToken());
	    }
	    var dataJson = JSON.stringify(data);
	    var cacheKey = md5(a.join('') + '-' + dataJson);

	    if (__api_call_list[cacheKey]) {
	        console.log(cacheKey + ' 请求中');
	        return __api_call_list[cacheKey].promise;
	    }

	    var url = this.GetPath(a.join(""));
	    var $this = this;
	    var p = new Promise(function (resolve, reject) {
	        if (cacheTimeOut > 0) {
	            var cache = $this.getCache(cacheKey);
	            if (cache !== null) {
	                console.log(cacheKey + ' 返回缓存');
	                resolve(cache);
	                __api_call_list[cacheKey] = null;
	                delete __api_call_list[cacheKey];
	                return;
	            }
	        }
	        $.ajax({
	            type: 'POST',
	            url: url,
	            data: data,
	            dataType: "json",
	            contentType: "application/json",
	            beforeSend: function () {
	            },
	            success: function (data) {
	                if (data == null) {
	                    reject({ "Success": false, "Message": '没有返回' });
	                } else if (data.Success) {
	                    if (cacheTimeOut > 0) {
	                        $this.setCache(cacheKey, data.Data, cacheTimeOut);
	                    }
	                    console.log(cacheKey + ' 请求成功');
	                    resolve(data.Data);
	                } else if (data.Success === false) {
	                    if (data.Code == 4009) {
	                        //window.parent.location.href = location.host + "/login.aspx";
	                        window.parent.location.href = "../login.aspx";
	                    } else {
	                        reject(data);
	                    }
	                } else {
	                    reject(data);
	                }
	                __api_call_list[cacheKey] = null;
	                delete __api_call_list[cacheKey];
	            }
	        });
	    });
	    __api_call_list[cacheKey] = {
	        promise: p
	    }
	    return p;
	}
	this.TestApi = function (control, action, data) {
	    this.API2(control, action, data, function (data) {
	        console.log(data);
	    });
	};
	this.API = function (url, data, callBack) {
	    if (this.UseAccessToken) {
	        if (/[\?&]token=/ig.test(url) === false) {
	            if (url.indexOf("?") >= 0) {
	                url += ("&token=" + this.getToken());
	            } else {
	                url += ("?token=" + this.getToken());
	            }
	        }
	    }
	    if (/[\?&]u=/ig.test(url) === false) {
	        if (url.indexOf("?") >= 0) {
	            url += ("&u=" + this.getUserToken());
	        } else {
	            url += ("?u=" + this.getUserToken());
	        }
	    }
	    $.ajax({
	        type: 'POST',
	        url: this.GetPath(url),
	        data: data,
	        dataType: "json",
	        contentType: "application/json",
	        beforeSend: function () {
	        },
	        success: function (data) {
	            if (callBack != null) {
	                if (data == null) {
	                    callBack({ "Success": false, "Message": '没有返回' });
	                } else if (data.Success) {
	                    callBack(data.Data);
	                } else if (data.Success === false) {
	                    if (data.Code == 4009) {
	                        //window.parent.location.href = location.host + "/login.aspx";
	                        window.parent.location.href = "../login.aspx";
	                    } else {
	                        reject(data);
	                    }
	                } else if ($.type(data.d) === "string") {
	                    callBack($.parseJSON(data.d));
	                } else {
	                    callBack(data.d);
	                }
	            }
	        }
	    });
	    return this;
	};
	this.APIToken = function (callBack) {
	    this.API("~/api.ashx?c=Token&a=Get&token=nokey", {
	        'appid': "45F96699-2744-4516-9A71-AE619739A868",
	        'secret': "13590650080"
	    }, function(data) {
	        if(data.Success === false) {
	            
	        }else {
	            localStorage.setItem("API-ACCESS-TOKEN", data.AccessToken);
	        }
            if($.isFunction(callBack)) {
                callBack(data);
            }
	    });
	};

	///页面初始时可能需要调用多个API请求数据，这时候使用此方法将合并请求
	///输入参数，至少要2个，是以下结构的对象，最后一个参数如果是function则为错误回调
	/*
	{
		"controller":"ccc",
		"action":"action",
		"data":{},
		"callBack":function(){}
	}
	*/
	this.InitAPI = function () {
		function check(obj) {
			if ($.isPlainObject(obj)) {
				if (obj.hasOwnProperty('controller') &&
					obj.hasOwnProperty('action')) {
					return true;
				}
			}
			return false;
		}

		var c = [];
		for (var i = 0; i < arguments.length; i++) {
			if (check(arguments[i])) c.push(arguments[i]);
		}
		if (c.length < 1) {
			throw new Error("参数太少");
		}

		var errCallBack = arguments.length > 2 ? (
			$.isFunction(arguments[arguments.length - 1])? arguments[arguments.length - 1]:null
			) : null;
		var callData = [];
		var callBackList = {};
		for (var i = 0; i < c.length; i++) {
			var d = c[i];
			var id = parseInt(Math.random().toString().substring(2));//(new Date()).getTime();
			if ($.isFunction(d.callBack)) {
			    callBackList[id] = d.callBack;
			}
			callData.push({
				"controller": d.controller,
				"action": d.action,
				"data": d.hasOwnProperty('data') ? $.param(d.data) : null,
				"ID": id
			});
		}
		this.API2('Core', 'Init', {
			"args":callData
		}, function(data) {
			if (data.Success == false) {
				if (errCallBack) errCallBack(data);
			} else {
				for (var i = 0; i < data.length; i++) {
					var item = data[i];
					if (item.hasOwnProperty('ID')) {
						var id = item.ID;
						if (callBackList[id]) {
							callBackList[id](item.Result);
						}
					}
				}
			}
		});
	};
	this.IsHasLogin = this.IsLogin = function (callBack) {
		$.ajax({
			type: 'POST',
			url: this.GetPath('~/Index/Index.aspx') + '/IsHasLogin',
			data:  '{CusID : ""}',
			dataType: "json",
			contentType: "application/json",
			success: function (data) {
				var da = $.parseJSON(data.d);
				if (da.err != "1") {
					$("#btnLogin_forJs").click();
				} else {
					if (callBack) callBack();
				}
			}
		});
		return this;
	}

	/**
	* 设置Cookie
	*/
	this.SetCookie = function (name, value, hours) {
		var expire = "";
		if (hours != null) {
			expire = new Date((new Date()).getTime() + hours * 3600000);
			expire = "; expires=" + expire.toGMTString();
		}
		if (document.domain == 'localhost')
			document.cookie = name + "=" + escape(value) + expire + ";path=/;";
		else
			document.cookie = name + "=" + escape(value) + expire + ";domain=" + document.domain + ";" + "path=/;";
	};
	/**
	 * 取Cookie
	 * @param name cookie名称
	 * @return string
	 */
	this.GetCookie = function (name) {
		var cookieValue = "";
		var search = name + "=";
		if (document.cookie.length > 0) {
			offset = document.cookie.indexOf(search);
			if (offset != -1) {
				offset += search.length;
				end = document.cookie.indexOf(";", offset);
				if (end == -1)
					end = document.cookie.length;
				cookieValue = unescape(document.cookie.substring(offset, end));
			}
		}
		return cookieValue;
	};
	this.BrowserIsSupport = function(){
        var u = navigator.userAgent, app = navigator.appVersion;
        return {//移动终端浏览器版本信息 
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
            iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
            };
    };
	this.GetDPR=function(){
		var dpr;
	    if(window.devicePixelRatio !== undefined) {
            dpr = window.devicePixelRatio;
        } else {
            dpr = 1;
        }
		return dpr;
	};
	this.TestCellphone = function(tel) {
	    return tel && /^(13|15|17|18)\d{9}$/.test(tel);
	};
	
	this.checkNull = function(obj) {
	    return typeof(obj) == 'undefined' || obj == null || obj == "";
	};

	this.NoData=function(obj,col) {
	    $(obj).empty().append('<tr class="gradeX footable-odd"><td><i class="fa fa-frown-o"></i></td><td colspan='+col+'>无数据</td></tr>');
	}

	this.fixLength = function (num,len){
		num+='';
		if(num.length<len){
			var t = len - num.length;
			var prefix= new Array( t + 1 ).join( '0' );
			return prefix+num;
		}else{
			return num;
		}
	};
	
	this.getDate = function (unixtime){
		var d = new Date();
		if(unixtime)
			d.setTime(unixtime);
		return d.getFullYear()+'-'+this.fixLength(parseInt(d.getMonth()+1),2)+'-'+this.fixLength(d.getDate(),2);
	};
	this.getDateTime = function (unixtime){
		var d = new Date();
		if(unixtime)
			d.setTime(unixtime);
		return d.getFullYear()+'-'+this.fixLength(parseInt(d.getMonth()+1),2)+'-'+this.fixLength(d.getDate(),2)+' '+this.fixLength(d.getHours(),2)+':'+Qing.fixLength(d.getMinutes(),2);
	};
	
	this.checkRequire = function(element) {
		if ($.trim($(element).val()) == '') {
			$(element).css('border-color', '#f10582');
			return false;
		} else {
			$(element).css('border-color', '#ccc');
			return true;
		}
	};
	//居中
	this.setToCenter = function (node,el,deltaX,deltaY){
		this.setToXCenter(node,el,deltaX);
		this.setToYCenter(node,el,deltaY);
	};
	this.setToYCenter = function (node,el,deltaY){
		var top  = ($(node).height() - $(el).outerHeight(true))/2;
		if(typeof deltaY !='undefined'){
			top+=deltaY;
		}
		$(el).css({'top':top+'px'});
	};
	this.setToXCenter = function (node,el,deltaX){
		
		var left = ($(node).width() - $(el).outerWidth(true))/2;
		if(typeof deltaX !='undefined'){
			left+=deltaX;
		}
		$(el).css({'left':left+'px'});
	};
    this.setHistory = function(url) {
        if (window.history.pushState == undefined) {
            this.SetCookie("lastUrl", url);
        } else {
            window.history.pushState({
                time: new Date().getTime()
            }, "", url);
        }
    }
    this.formatFloat = function (f, size)
    {
        var tf = f * Math.pow(10, size);
        tf = Math.round(tf + 0.000000001);
        tf = tf / Math.pow(10, size);
        return tf;

    };
    this.formatZero = function (f) {
        if (parseFloat(f) == 0) {//0不做小数处理
            return 0;
        }
        return f;
    };
    window.Y = this;
	if (location.pathname.toLowerCase().indexOf('/admin/') >= 0) {
	    if (window.top === window) {
	        if (location.pathname.toLowerCase().endsWith('/admin/index.aspx')) {
	            var url = sessionStorage.getItem('--to-iframe--');
	            if (url && url.length > 1) {
	                //$("#MainFrame").attr("src", url);
	                this.gotoIFrame = url;
	            }
	            sessionStorage.removeItem('--to-iframe--');
	        } else {
	            sessionStorage.setItem('--to-iframe--', location.pathname + location.search);
	            this.SetCookie('lastUrl', '');
	            location.href = '/Admin/Index.aspx';
	        }
	    }else{
			if (location.pathname.toLowerCase().endsWith('/admin/index.aspx')) {
				window.top.location.href = '/Admin/Index.aspx';
			}
		}
	}
	//console.log(window.Y);
}

window.Kmer.Uploader = function (options) {
    var option = {
        Debug: true,
        el: null,
        AutoUpload: true,
        UploadUrl: '/api/Image.ashx/Upload',
        Path: 'MIX',
        MaxFileLength: 5 * 1024 * 1024,
        OnUploadBeginning: null,
        OnProgress: null,
        OnError: null,
        OnComplete: null,
        OnAllComplete: null,
        checkImageSize: null
    };
    $.extend(option, options);
    if (option.el == null) {
        console.error("请指定el");
        throw new Error("请指定el");
    }
    var $this = this;
    var toUploadFiles = [];
    var uploadFile = null;
    function onProgress(file, pc) {
        if (typeof option.OnProgress === "function") {
            option.OnProgress.call($this, file, pc);
        }
        if (option.Debug) {
            console.log('uploading...', file.name, pc);
        }
    }
    function onComplete(succ, file, xhr) {
        if (succ) {
            if (option.Debug) {
                console.log('上传成功', file, xhr);
            }
            if (typeof option.OnComplete === "function") {
                option.OnComplete.call($this, file, $.parseJSON(xhr.responseText));
            }
        } else {
            if (option.Debug) {
                console.error('上传失败：', file);
            }
            if (typeof option.OnError === "function") {
                option.OnError.call($this, file);
            }
        }
        if (toUploadFiles.length > 0) {
            var f = toUploadFiles.pop();
            uploadFile(f);
        } else {
            if (option.Debug) {
                console.log('全部上传成功');
            }
            if (typeof option.OnAllComplete === "function") {
                option.OnAllComplete.call($this);
            }
        }
    }

    function testImg(file, callBack) {
        var reader = new FileReader();
        reader.onload = function () {
            var url = reader.result;
            var image = new Image();
            image.onload = function (e) {
                if (typeof option.checkImageSize === "function") {
                    //if ($.isFunction($this.option.checkImageSize)) {
                    var r = option.checkImageSize(this.width, this.height);
                    callBack(r);
                } else {
                    callBack(true);
                }
            }
            image.src = url;
        };
        reader.readAsDataURL(file);
    }

    uploadFile = function (file) {
        var xhr = new XMLHttpRequest();
        //&& file.type === "image/jpeg"
        if (xhr.upload && file.size <= option.MaxFileLength) {
            xhr.upload.addEventListener("progress", function (e) {
                var pc = parseInt(e.loaded / e.total * 100);
                onProgress(file, pc);
            }, false);

            xhr.onreadystatechange = function (e) {
                if (xhr.readyState == 4) {
                    onComplete(xhr.status == 200, file, xhr);
                }
            };

            // start upload
            xhr.open("POST", option.UploadUrl + '?basePath=' + option.Path + '&fn=' + file.name, true);
            xhr.setRequestHeader("X_FILENAME", 'AJAX');
            if (option.Debug) {
                console.log('开始上传：', file);
            }
            if (typeof option.OnUploadBeginning === "function") {
                option.OnUploadBeginning.call($this, file);
            }
            xhr.send(file);
        } else {
            onComplete(false, file, xhr);
        }
    }

    // file drag hover
    function fileDragHover(e) {
        e.stopPropagation();
        e.preventDefault();
        e.target.className = (e.type == "dragover" ? "hover" : "");
    }
    function beginUpload() {
        if (toUploadFiles.length > 0) {
            var f = toUploadFiles.pop();
            uploadFile(f);
        }
    }
    // file selection
    function fileSelectHandler(e) {
        fileDragHover(e);
        var files = e.target.files || e.dataTransfer.files;
        toUploadFiles = [];
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            testImg(file, function (r) {
                if (r) {
                    toUploadFiles.push(file);
                    beginUpload();
                }
            });
        }
    }
    var bindFileControl = function (el) {
        var file = $(el);
        if (file.length == 0) {
            console.error("错误！没找到：", el);
            return;
        }
        if (file.filter('input[type=file]').length == 0 && file.find('input[type=file]').length == 0) {
            console.error('错误！没找到<input type="File" />', el);
            return;
        }
        console.log(file.filter('input[type=file]').first());
        file.filter('input[type=file]').first().change(function (e) {
            fileSelectHandler(e);
        });
        if (file.children().length > 0) {
            file.find('input[type=file]').first().change(function (e) {
                fileSelectHandler(e);
            });
        }
    }
    bindFileControl(option.el);
}
function a($) {
    var Paginator = function (element, options) {
        this.init(element, options);
    };
    Paginator.prototype = {
        init: function (el, options) {
            this.$element = $(el);
            this.setOptions(options);
            this.listen();
        },
        listen: function () {
            this.$element.off("page-clicked");
            this.$element.off("page-changed");// unload the events for the element
            if (typeof (this.options.onPageClicked) === "function") {
                this.$element.bind("page-clicked", this.options.onPageClicked);
            }
            if (typeof (this.options.onPageChanged) === "function") {
                this.$element.on("page-changed", this.options.onPageChanged);
            }
            this.$element.bind("page-clicked", this.onPageClicked);
        },
        setOptions: function (options) {
            this.options = $.extend({}, (this.options || $.fn.Paginator.defaults), options);
            this.options.Page = Math.max(1, this.options.Page);
            this.options.PageSize = Math.max(1, this.options.PageSize);
            this.options.PageCount = Math.max(1, this.options.PageCount);
            console.log(this.options);
            this.render();
        },
        render: function () {
            this.$element.prop("class", "");
            this.$element.addClass("pagination");

            var pi = this.options.Page;
            var sb = this.$element;
            sb.empty();
            if (this.options.PageCount > 5)
            if (this.options.Show.First || this.options.Show.Prev){
                if (pi > 1) {
                    if (this.options.Show.First)
                        sb.append($('<li><a href="javascript:;" title="第一页">&nbsp;<i class="fa fa-fast-backward"></i>&nbsp;</a></li>').attr('data-page', 1));
                    if (this.options.Show.Prev)
                        sb.append($('<li><a href="javascript:;" title="上一页">&nbsp;<i class="fa fa-backward"></i>&nbsp;</a></li>').attr('data-page', pi + 1));
                } else {
                    if (this.options.Show.First)
                        sb.append($('<li class="disabled"><a href="javascript:;" title="第一页">&nbsp;<i class="fa fa-fast-backward"></i>&nbsp;</a></li>'));
                    if (this.options.Show.Prev)
                        sb.append($('<li class="disabled"><a href="javascript:;" title="上一页">&nbsp;<i class="fa fa-backward"></i>&nbsp;</a></li>'));
                }
            }

            if (this.options.PageCount < 6) {
                for (var i = 1; i <= this.options.PageCount; i++) {
                    if (pi == i) {
                        sb.append($('<li class="active"><a href="javascript:;">0</a></li>').find('a').text(i).parent());
                    } else {
                        sb.append($('<li><a href="javascript:;">0</a></li>').find('a').text(i).parent().attr('data-page', i));
                    }
                }
            }else {
                var si = Math.max(pi - 2, 1);
                var ei = Math.min(si + 4, this.options.PageCount);
                if (si > this.options.PageCount - 4) {
                    si = this.options.PageCount - 4;
                }
                for (var i = si; i <= ei; i++) {
                    if (pi == i) {
                        sb.append($('<li class="active"><a href="javascript:;">0</a></li>').find('a').text(i).parent());
                    } else {
                        sb.append($('<li><a href="javascript:;">0</a></li>').find('a').text(i).parent().attr('data-page', i));
                    }
                }
            }
            if (this.options.PageCount > 5)
            if (this.options.Show.Next || this.options.Show.Last) {
                if (pi < this.options.PageCount) {
                    if (this.options.Show.Next)
                        sb.append($('<li><a href="javascript:;" title="下一页">&nbsp;<i class="fa fa-forward"></i>&nbsp;</a></li>').attr('data-page', pi + 1));
                    if (this.options.Show.Last)
                        sb.append($('<li><a href="javascript:;" title="最后一页">&nbsp;<i class="fa fa-fast-forward"></i>&nbsp;</a></li>').attr('data-page', this.options.PageCount));
                } else {
                    if (this.options.Show.Next)
                        sb.append('<li class="disabled"><a href="javascript:;" title="下一页">&nbsp;<i class="fa fa-forward"></i>&nbsp;</a></li>');
                    if (this.options.Show.Last)
                        sb.append('<li class="disabled"><a href="javascript:;" title="最后一页">&nbsp;<i class="fa fa-fast-forward"></i>&nbsp;</a></li>');
                }
            }
            sb.find('li[data-page]').click(function(event) {
                var page = $(this).data('page');
                var type = event.type;
                sb.trigger("page-clicked", [event, type, page]);
            });
        }
    }
    $.fn.Paginator = function (option) {
        var args = arguments,
            result = null;

        $(this).each(function (index, item) {
            var $this = $(item),
                data = $this.data('Paginator'),
                options = (typeof option !== 'object') ? null : option;
            if (!data) {
                data = new Paginator(this, options);
                $this = $(data.$element);
                $this.data('Paginator', data);
                return;
            }
            if (typeof option === 'string') {
                if (data[option]) {
                    result = data[option].apply(data, Array.prototype.slice.call(args, 1));
                } else {
                    throw "Method " + option + " does not exist";
                }
            } else {
                result = data.setOptions(option);
            }
        });
        return result;
    }
    $.fn.Paginator.defaults = {
        Page: 1,
        PageSize: 10,
        PageCount: 1,
        Show: {
            First: true,
            Prev: true,
            Next: true,
            Last: true
        },
        UseCookie:true,
        onPageClicked:null
    };
};a(jQuery);

//--------
QingApp={};
/**
 * 计算现在时间与指定的时间段相差关系
 * @string startTime 开始时间，格式如：2015-11-11 11:11:11
 * @string endTime 结束时间，格式如：2015-11-11 11:11:11
 * 返回值说明：
 *          -1 已结束，现在时间大于结束时间
 *          {date:日期,day:天数,hour:小时,minute:分,second:秒,state:状态} state=wait表示未开始,state=processing表示进行中
 */
QingApp.getDeadlineTime = function(startTime,endTime){
	function _getDate(time){
		var month = time.substr(5,2);
		month = parseInt(month) - 1;
    	return new Date(time.substr(0,4),month,time.substr(8,2),time.substr(11,2),time.substr(14,2),time.substr(17,2),999);
	}
	//取得现在时间
	//--需要服务器校准后的时间
	function _getNowDate(){
		if(!window.SVRTIME_DELTA){
			Y.API2('Tool','GetTime',{"type":0}, function(data){
				var localDate = new Date();
				window.SVRTIME_DELTA = parseInt(data) - localDate.getTime();
			});
			return new Date();	
		}else{
			var localDate = new Date();
			localDate.setTime(localDate.getTime()+window.SVRTIME_DELTA);
			return localDate;
		}
	}
	if(typeof type=='undefined'){
		type = 1;
	}
	var startDate =  _getDate(startTime);
	var endDate   = _getDate(endTime);
	//现在时间
	var nowDate   = _getNowDate();
	
	if(nowDate.getTime()>endDate.getTime()){
		//已结束
		return -1;
	}

	var daysMs = 24 * 60 * 60 * 1000;
	var hoursMs = 60 * 60 * 1000;
	var minuteMs = 60 * 1000;
	var secondMs = 1000;

	var hour = nowDate.getHours()
	var minute = nowDate.getMinutes()
	var second = nowDate.getSeconds();
	var state   = '';
	var caculateDate;
	//未开始时统一按开始时间来对比
	if(nowDate.getTime() < startDate.getTime()){
		caculateDate = startDate;
		state = 'wait';
	}else{
		caculateDate = endDate;
		state = 'processing';
	}

	var diffMs = caculateDate.getTime() - nowDate.getTime();

	var restDay = Math.floor(diffMs / daysMs);

	var restMs  = (diffMs - restDay * daysMs);
	var restHour=  Math.floor(restMs / hoursMs);

    restMs -= restHour * hoursMs;
    var restMinute =  Math.floor(restMs / minuteMs);

    restMs -= restMinute * minuteMs;
    var restSecond =  Math.floor(restMs / secondMs);
    
	restMs -= restSecond * secondMs;
	
    restHour=restHour>9?restHour:'0'+restHour;
    restMinute=restMinute>9?restMinute:'0'+restMinute;
    restSecond=restSecond>9?restSecond:'0'+restSecond;
    var startD = parseInt(caculateDate.getMonth()+1)+'月'+caculateDate.getDate()+'日';
    var startDateObject = caculateDate;

	if(nowDate.getTime() >=startDate.getTime() ){
		//还剩余多久结束
		return {date:startD,dateObject:startDateObject,day:restDay,hour:restHour,minute:restMinute,second:restSecond,msSecond:restMs,'state':'processing'};
	}else{
		//未开始，还有多久开始
		return {date:startD,dateObject:startDateObject,day:restDay,hour:restHour,minute:restMinute,second:restSecond,msSecond:restMs,'state':'wait'};
	}
	
};
QingApp.apiPost = function (mod,act,param,callback,errorCallback){
	Y.API2(mod,act,param,function(resp){
		console.log(resp);
		if(resp.Success==false){
			if(typeof callback=='function'){
				errorCallback(resp);
			}	
		}else{
		    if(typeof callback=='function'){
				callback(resp);
			}
		}
	});
}
QingApp.LoadDataDefaultOption = {
	enableScrollLoad:true, //启用滚动加载
	apiParam:null,  //传参对象，用json对象
	beforeLoad:null,  //加载之前要执行的函数
	apiModule:'',     //api Module
	apiAction:'',     //api action
	perPage:10,       //每页显示条数
	indicator:'',     //指示对象,内容是loadingMsg
	loadingMsg:'<i class="fa fa-spinner fa-spin"></i> 正在加载......',
	noDataMsg:'暂无记录',
	errorMsg:'',
	loadSuccessCallback:null,    //加载成功后要执行的函数方法
	loadFailureCallback:null,    //加载失败时要执行的函数方法
	scroller:window    //需要滚动的对象，默认用window
};
QingApp.refreshLoadData = function(opt){
	var option =$.extend({},$('body').data('QingApp.loadData.option'),opt);
	QingApp.loadData(option);
};
QingApp.loadData = function(opt){
	var loading = false;
	var option  = $.extend({},QingApp.LoadDataDefaultOption,opt);
	$('body').data('QingApp.loadData.page',1);
	$('body').data('QingApp.loadData.totalPage',0);
	$('body').data('QingApp.loadData.option',option);
	_loadData(1);
	if(option.enableScrollLoad){
		$(option.scroller).scroll(function(){
			var WindowHeight = $(option.scroller).outerHeight(); /* get the window height */
			var scrollHeight = $(option.scroller).get(0).scrollHeight;
			var scrollTop    = $(option.scroller).scrollTop();
			//console.log('scrollHeight:'+scrollHeight);
			//console.log('scrollTop:'+scrollTop);
			//console.log('WindowHeight:'+WindowHeight);
			if(scrollHeight - scrollTop - WindowHeight<=100) {
	        //if(($(document).height() - WindowHeight - $(window).scrollTop()) /WindowHeight < 0.2) {
	            var page      = $('body').data('QingApp.loadData.page');
	        	var totalPage = $('body').data('QingApp.loadData.totalPage');
	        	if(totalPage>page && !loading){
	        		page++;
	        		_loadData(page);
	        	}
			}
		});
	}
	function _loadData(page){
		var option = $('body').data('QingApp.loadData.option');
		if(typeof option.beforeLoad =='function'){
			option.beforeLoad.apply(null);
		}
		loading = true;
		if(option.indicator && $(option.indicator).length>0){
			$(option.indicator).html(option.loadingMsg).show();
		}
		if(!option.apiParam){
			option.apiParam = {};
		}
		option.apiParam.Size= option.perPage;
		option.apiParam.Page = page;
		$('body').data('QingApp.loadData.option',option);
		QingApp.apiPost(option.apiModule,option.apiAction,option.apiParam,function(resp){
			var totalPage = 0;
			var total = 0;
			if(typeof resp.Total!='undefined'){
				totalPage = Math.ceil(resp.Total / option.perPage);
				total     = resp.Total;
				$('body').data('QingApp.loadData.totalPage',totalPage);
			}
			$('body').data('QingApp.loadData.page',page);
			if(option.indicator && $(option.indicator).length>0){
				if(totalPage>page){
					$(option.indicator).hide();
				}else if(totalPage==page && page!=0){
					$(option.indicator).html('<div class="heading heading-v3"><h2 class="heading-xs">共'+total+'条记录，已全部显示</h2></div>');
				}else if(resp.error || (typeof resp.List!='undefined' && resp.List.length==0)){
					$(option.indicator).html('<div class="heading heading-v3"><h2 class="heading-xs">暂无记录</h2></div>');
				}
			}
			if(typeof option.loadSuccessCallback=='function'){
				option.loadSuccessCallback(resp);
			}
			loading = false;
		},function(){
			loading = false;
			if(typeof option.loadFailureCallback=='function'){
				option.loadFailureCallback.apply(null);
			}
			if(option.indicator && $(option.indicator).length>0){
				if(option.errorMsg){
					$(option.indicator).html('<div class="heading heading-v3"><h2 class="heading-xs">'+option.errorMsg+'</h2></div>');
				}else{
					$(option.indicator).hide();
				}
			}
		});
	}
};


